<?php

declare(strict_types=1);
/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/5/29.
 */

namespace App\Http\Controllers\Traits;

use App\Exceptions\CommonExceptionConstants;
use App\Exceptions\ServiceException;
use App\Utils\ResultsVo;

trait ExtendTrait
{
    /**
     * 删除数据.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(): \Illuminate\Http\JsonResponse
    {
        $model = modelBuild($this->getModel());
        $model->newQuery()->whereIn($model->getKeyName(), $this->getIds())->delete();

        return ResultsVo::success();
    }

    /**
     * 恢复被删除后的数据.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function restore(): \Illuminate\Http\JsonResponse
    {
        $model = modelBuild($this->getModel());
        $model->newQuery()->whereIn($model->getKeyName(), $this->getIds());
        if (method_exists($model, 'restore')) {
            $model->restore();

            return ResultsVo::success();
        }

        return ResultsVo::error('未定义回收站恢复方法！');
    }

    /**
     * 如果状态改变是多选 则需要传递状态值，
     * 状态切换，只有0，1两种状态的时候 可以使用这个方法.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function status(): \Illuminate\Http\JsonResponse
    {
        $ids = $this->getIds();
        $model = modelBuild($this->getModel());
        $field = request()->get('field', 'status');
        $fields = $model->getTableFields();
        // 当字段不存在时需要提示错误
        if (!\in_array($field, $fields, true)) {
            throw new ServiceException("字段：【{$field}】未在数据表中定义");
        }
        if (1 === \count($ids)) {
            $id = reset($ids);
            $dao = $model->newQuery()->where($model->getKeyName(), $id)->first();
            $dao->{$field} = !$dao->{$field};
            $dao->save();

            return ResultsVo::success();
        }
        $val = request()->get('value');
        $model->newQuery()->whereIn($model->getKeyName(), $ids)->update([
            $field => $val,
        ]);

        return ResultsVo::success();
    }

    /**
     * 单字段编辑支持
     *
     * @param mixed $id
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function editField($id): \Illuminate\Http\JsonResponse
    {
        $model = modelBuild($this->getModel());
        $field = request()->get('field', 'status');
        $value = request()->get('value');
        $fields = $model->getTableFields();
        // 当字段不存在时需要提示错误
        if (!\in_array($field, $fields, true)) {
            throw new ServiceException("数据表中不存在的字段信息：【{$field}】");
        }
        $dao = $model->newQuery()->find($id);
        if (!$dao) {
            throw new ServiceException(CommonExceptionConstants::NO_FIND_DATA);
        }
        $dao->{$field} = $value;
        $dao->save();

        return ResultsVo::success();
    }
}
